<template>
  <view>
    <BaseNavbar :title="title" />
    <BaseTabs :current="curTabIndex" :list="tabList" @change="tabChange" />
    <view class="content">
      <!--判断是哪个类型  来显示不同的设置广告模式   strat  -->
      <view class="content-device" v-if="curTabIndex === 0">
        <view class="title">设备编号</view>
        <view class="txt">
          <BaseInput v-model="device_sn" :disabled="true" />
        </view>
      </view>
      <view class="content-device" v-if="curTabIndex === 1">
        <view class="title">选择设备</view>
        <view class="txt">
          <BaseInput
            v-model="modelDeviceList"
            :disabled="true"
            placeholder="请选择设备"
            @onClick="goSelectInfo"
          />
        </view>
        <view class="device-list">
          <view
            class="device-list-item"
            v-for="(item, index) in deviceSnList"
            :key="item.id"
          >
            <view class="device-list-item-left">{{ item.device_sn }}</view>
            <view class="device-list-item-right" @click="delDevice(index)">
              <BaseIcon name="close-circle" size="38" />
            </view>
          </view>
        </view>
      </view>
      <view class="content-device" v-if="curTabIndex === 2">
        <view class="title">选择{{ vPointName }}</view>
        <view class="txt">
          <BaseInput
            v-model="selectPlaceInfo.hotelName"
            :disabled="true"
            :placeholder="'请选择'+vPointName"
            @onClick="goSelectInfo"
          />
        </view>
      </view>
      <view class="content-device" v-if="curTabIndex === 3">
        <view class="title">编辑自己的所有设备</view>
      </view>

      <!--判断是哪个类型  来显示不同的设置广告模式 end  -->

      <block v-for="(obj, keys) in info" :key="keys">
        <view class="content-box">
          <view class="content-box-title">
            <view class="title">{{ keyObj[keys].name }}</view>
            <view class="right">
              <view class="add-ad" @click="addAd(keys)">添加广告</view>
            </view>
          </view>
          <view class="content-box-main" v-if="isShowArrow(obj)">
            <block v-if="keyObj[keys].type === 'swiper'">
              <view class="content-box-main-item">
                <swiper class="swiper-box" :indicator-dots="true">
                  <swiper-item v-for="(item, index) in obj" :key="item.id">
                    <view>
                      <text user-select="true">
                        广告链接：{{ item.img_href }}
                      </text>
                    </view>
                    <image
                      v-if="item.file_type == 1"
                      @click="previewImage(item.img_url)"
                      class="img"
                      :src="item.img_url"
                    />
                    <video
                      v-else-if="item.file_type == 2"
                      class="img"
                      :src="item.img_url"
                    />
                    <view class="clear" @click="emptyAd(obj, keys, index)">
                      <BaseIcon
                        name="close-circle-fill"
                        size="58"
                        color="#EF0000"
                      />
                    </view>
                  </swiper-item>
                </swiper>
              </view>
            </block>
            <block v-if="keyObj[keys].type === 'wx-swiper'">
              <view class="content-box-main-item">
                <swiper class="swiper-box" :indicator-dots="true">
                  <swiper-item v-for="(item, index) in obj" :key="item.id">
                    <view>
                      <text user-select="true">
                        公众号名称：{{ item.app_name }}
                      </text>
                    </view>
                    <image
                      class="img"
                      @click="previewImage(item.wx_img)"
                      :src="item.wx_img"
                    />

                    <view class="clear" @click="emptyAd(obj, keys, index)">
                      <BaseIcon
                        name="close-circle-fill"
                        size="58"
                        color="#EF0000"
                      />
                    </view>
                  </swiper-item>
                </swiper>
              </view>
            </block>

            <block v-if="keyObj[keys].type === 'img'">
              <view class="content-box-main-item">
                <view>
                  <text user-select="true">广告链接：{{ obj.img_href }}</text>
                </view>

                <view class="box-img">
                  <image
                    v-if="obj.file_type == 1"
                    class="img"
                    :src="obj.img_url"
                    @click="previewImage(obj.img_url)"
                  />
                  <video
                    v-else-if="obj.file_type == 2"
                    class="img"
                    :src="obj.img_url"
                  />
                  <view class="clear" @click="emptyAd(obj, keys)">
                    <BaseIcon
                      name="close-circle-fill"
                      size="58"
                      color="#EF0000"
                    />
                  </view>
                </view>
              </view>
            </block>
            <block v-else-if="keyObj[keys].type === 'wx-img'">
              <view class="content-box-main-item">
                <view>
                  <text user-select="true">小程序名称：{{ obj.app_name }}</text>
                </view>
                <view class="box-img">
                  <image
                    class="img"
                    :src="obj.wx_img"
                    @click="previewImage(obj.wx_img)"
                  />
                  <view class="clear" @click="emptyAd(obj, keys)">
                    <BaseIcon
                      name="close-circle-fill"
                      size="58"
                      color="#EF0000"
                    />
                  </view>
                </view>
              </view>
            </block>
            <block v-else-if="keyObj[keys].type === 'txt'">
              <view class="content-box-main-item content-txt">
                <view> 屏幕滚动文字：{{ obj.content_text || "暂无" }} </view>
                <view
                  class="clear"
                  @click="emptyAd(obj, keys)"
                  v-if="obj.content_text"
                >
                  <BaseIcon
                    name="close-circle-fill"
                    size="58"
                    color="#EF0000"
                  />
                </view>
              </view>
            </block>
          </view>
        </view>
      </block>
    </view>
    <!-- 占位safe -->
    <view :style="{ height: 120 + vIphoneXBottomHeight + 'rpx' }"></view>
    <view
      class="fixed-btn flexRowBetween"
      :style="{ paddingBottom: 20 + vIphoneXBottomHeight + 'rpx' }"
    >
      <BaseButton width="690" type="primary" @onClick="confirmOrder">
        {{ btnTitle }}
      </BaseButton>
    </view>
  </view>
</template>

<script>
import BaseNavbar from "../../components/base/BaseNavbar.vue";
import BaseInput from "../../components/base/BaseInput.vue";
import BaseIcon from "../../components/base/BaseIcon.vue";
import BaseButton from "../../components/base/BaseButton.vue";
import BaseTabs from "../../components/base/BaseTabs.vue";
export default {
  components: {
    BaseNavbar,
    BaseInput,
    BaseIcon,
    BaseButton,
    BaseTabs,
  },
  computed: {
    modelDeviceList() {
      return this.deviceSnList?.map((item) => item.device_sn)?.join(";");
    },
    tabList() {
      return [
        {
          name: "设备编辑",
          type: 0,
        },
        {
          name: "设备批量编辑",
          type: 1,
        },
        {
          name: `${this.vPointName}设备编辑`,
          type: 2,
        },
        {
          name: "用户设备编辑",
          type: 3,
        },
      ];
    },
  },
  data() {
    return {
      title: "新增设备广告",
      device_sn: "",
      mid: "",
      fromData: "",
      isFromEdit: false,
      isFromAdd: false,
      //默认的数据，便于切换重置
      defaultInfo: {
        alert_index: null,
        alert_pay: null,
        bottom_index: null,
        index_suspension: null,
        pay_push: null,
        screen: [],
        send_mp: null,
        send_mp_free: null,
        send_mp_free_video: null,
        send_mp_jump: null,
        slide: [],
        top_txt: null,
        wx_list: [],
      },
      deviceEditInfo: {},
      info: {},
      keyObj: {
        slide: {
          name: "H5轮播广告",
          type: "swiper",
        },
        alert_index: {
          name: "H5首页弹窗",
          type: "img",
        },
        index_suspension: {
          name: "H5首页悬浮",
          type: "img",
        },
        alert_pay: {
          name: "H5付款完成弹窗",
          type: "img",
        },
        pay_push: {
          name: "完成微信推送广告",
          type: "img",
        },
        screen: {
          name: "屏幕轮播广告",
          type: "swiper",
        },
        bottom_index: { name: "屏幕底部广告", type: "img" },
        top_txt: {
          name: "屏幕顶部文字",
          type: "txt",
        },
        wx_list: {
          name: "屏幕公众号",
          type: "wx-swiper",
        },
        send_mp: {
          name: "推送小程序",
          type: "wx-img",
        },
        send_mp_free: {
          name: "免费小程序",
          type: "wx-img",
        },
        send_mp_free_video: {
          name: "视频小程序",
          type: "wx-img",
        },
        send_mp_jump: {
          name: "转跳小程序",
          type: "wx-img",
        },
      },
      btnTitle: "确认提交",
      selectKeys: "", //当前选择的key
      curTabIndex: 0,
      deviceSnList: [], //选择的 所有设备信息
      selectPlaceInfo: {}, //选择的点位信息
    };
  },
  methods: {
    //获取单个设备绑定的广告
    bindAdvertOne() {
      let data = { device_sn: this.device_sn };

      this.$u.api.bindAdvertOne(data).then((res) => {
        this.deviceEditInfo = {};
        //剔除返回对象中的 数字类名对象
        for (let i in res) {
          if (
            Number.isNaN(+i) &&
            i != "screen_count" &&
            i != "slide_count" &&
            i != "wx_count"
          ) {
            this.deviceEditInfo[i] = res[i];
          }
        }
        this.info = this.deviceEditInfo;
      });
    },
    //清空广告位
    emptyAd(item, keys, index) {
      console.log("🚀 ~ item", item);
      if (this.isFromEdit) {
        let id = null;
        if (this.keyObj[keys].type === "swiper") {
          id = item[index]?.id;
        } else {
          id = item?.id;
        }
        console.log("🚀 ~ id ", id);
        let data = { id };

        this.$u.api.bindDelete(data).then((res) => {
          this.updateInfo(item, keys, index);
        });
      } else {
        this.updateInfo(item, keys, index);
      }
    },
    updateInfo(item, keys, index) {
      if (this.keyObj[keys].type === "swiper") {
        this.info[keys].splice(index, 1);
      } else {
        this.info[keys] = null;
      }
      this.$forceUpdate();
    },
    // 有数据显示， 无数据隐藏
    isShowArrow(e) {
      if (!e) return false;
      if (Array.isArray(e)) {
        return e?.length > 0 ? true : false;
      } else {
        return true;
      }
    },
    //预览图片
    previewImage(urls) {
      uni.previewImage({
        urls: [urls],
      });
    },
    //确认提交
    async confirmOrder() {
      let rtn = null;
      let newObjInfo = {};
      let oldObjInfo = this.info;
      let nowKeyObj = this.keyObj;
      for (let i in oldObjInfo) {
        if (
          (nowKeyObj[i].type === "swiper" ||
            nowKeyObj[i].type === "wx-swiper") &&
          oldObjInfo[i]?.length > 0
        ) {
          oldObjInfo[i]?.forEach((item, index) => {
            !newObjInfo[i] && (newObjInfo[i] = []);

            newObjInfo[i].push({
              aid: item.aid,
              gid: item.gid || index,
            });
          });
        } else {
          if (oldObjInfo[i]?.aid) {
            newObjInfo[i] = oldObjInfo[i]?.aid;
          }
        }
      }

      console.log("🚀 ~ newObjInfo", newObjInfo);

      if (this.curTabIndex === 0) {
        if (this.isFromEdit) {
          let data = {
            mid: this.mid,
            ...newObjInfo,
          };
          rtn = await this.$u.api.bindAdvertPost(data);
        }
      } else if (this.curTabIndex === 1) {
        let mids = this.deviceSnList?.map((item) => item.id);
        let data = {
          mids,
          ...newObjInfo,
        };
        rtn = await this.$u.api.bindAdvertMachinePost(data);
      } else if (this.curTabIndex === 2) {
        let data = {
          hotel_id: this.selectPlaceInfo.id,
          ...newObjInfo,
        };
        rtn = await this.$u.api.bindAdvertHotelPost(data);
      } else if (this.curTabIndex === 3) {
        console.log("执行用户设置");
        let data = {
          ...newObjInfo,
        };
        rtn = await this.$u.api.bindAdvertUserPost(data);
        console.log("🚀 ~ rtn", rtn);
      }

      if (rtn) {
        this.isShowSuccess("设置成功", 1, null, true);
      }
    },
    //选择广告
    addAd(keys) {
      console.log("🚀 ~ keys", keys);
      this.selectKeys = keys;
      let nowKeyObj = this.keyObj;
      if (
        nowKeyObj[keys].type === "swiper" ||
        nowKeyObj[keys].type === "txt" ||
        nowKeyObj[keys].type === "img"
      ) {
        uni.navigateTo({
          url: "/pagesB/advertsManage/AdvertsManage?from=deivce_adverts",
        });
      } else if (
        nowKeyObj[keys].type === "wx-swiper" ||
        nowKeyObj[keys].type === "wx-img"
      ) {
        let type = nowKeyObj[keys].type === "wx-swiper" ? 0 : 1;
        uni.navigateTo({
          url: "/pagesB/wechat/Wechat?from=ad_select_wechat&type=" + type,
        });
      }
    },
    //处理选择广告函数
    setSelectAd(item) {
      console.log("🚀 ~ item", item);
      let keys = this.selectKeys;
      let nowKeyObj = this.keyObj;
      if (
        nowKeyObj[keys].type === "swiper" ||
        nowKeyObj[keys].type === "wx-swiper"
      ) {
        !Array.isArray(this.info[keys]) && (this.info[keys] = []);
        let newItem = {
          aid: item.id,
        };
        if (nowKeyObj[keys].type === "swiper") {
          newItem["img_url"] = item.img_url;
          newItem["img_href"] = item.img_href;
          newItem["file_type"] = item.file_type;
        } else if (nowKeyObj[keys].type === "wx-swiper") {
          newItem["app_name"] = item.app_name;
          newItem["wx_img"] = item.wx_img;
        }
        this.info[keys]?.push(newItem);
      } else if (
        nowKeyObj[keys].type === "img" ||
        nowKeyObj[keys].type === "wx-img"
      ) {
        this.info[keys] = {};
        let newItem = {
          aid: item.id,
        };
        if (nowKeyObj[keys].type === "img") {
          newItem["img_url"] = item.img_url;
          newItem["img_href"] = item.img_href;
          newItem["file_type"] = item.file_type;
        } else if (nowKeyObj[keys].type === "wx-img") {
          newItem["app_name"] = item.app_name;
          newItem["wx_img"] = item.wx_img;
        }
        this.info[keys] = newItem;
      } else if (nowKeyObj[keys].type === "txt") {
        this.info[keys] = {
          aid: item.aid,
          content_text: item.content_text,
        };
      }
      console.log("🚀 ~ this.info", this.info);
      this.$forceUpdate();
    },
    tabChange(i) {
      this.curTabIndex = i;
      if (i === 0) {
        this.info = this.deviceEditInfo;
      } else {
        this.info = this.defaultInfo;
      }
    },
    //去选择
    goSelectInfo() {
      if (this.curTabIndex === 2) {
        uni.navigateTo({ url: `/pagesB/place/PlaceList?from=ad_select_place` });
      } else if (this.curTabIndex === 1) {
        uni.navigateTo({
          url: `/pagesB/deviceAdverts/DeviceAdverts?from=ad_select_device`,
        });
      }
    },
    delDevice(i) {
      this.deviceSnList?.splice(i, 1);
    },
  },
  onLoad(opt) {
    this.fromData = opt?.from;
    if (opt?.from === "edit") {
      this.title = "编辑设备广告";
      this.btnTitle = "保   存";
      this.device_sn = opt?.device_sn;
      this.mid = opt?.mid;
      this.isFromEdit = true;
      this.bindAdvertOne();
    } else {
      this.title = "绑定设备广告";
      this.isFromAdd = true;
      this.btnTitle = "添   加";
    }
  },
  onShow() {
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1]; // 当前页
    if (currPage.data.item) {
      this.setSelectAd(currPage.data.item);
    }
    if (currPage.data.ad_select_item) {
      this.selectPlaceInfo = currPage.data.ad_select_item;
      console.log("🚀 ~  this.selectPlaceInfo ", this.selectPlaceInfo);
    }
    if (currPage.data.ad_select_device) {
      this.deviceSnList = currPage.data.ad_select_device;
    }
  },
};
</script>

<style lang="scss" scoped>
.content {
  padding: 20rpx;

  &-device {
    margin-bottom: 30rpx;
    .title {
      font-size: $font-size-xxxlarge;
      font-weight: 700;
      color: $textBlack;
      margin-bottom: 20rpx;
    }
    .device-list {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      &-item {
        width: 48%;
        display: flex;
        align-items: center;
        height: 76rpx;
        color: $textBlack;
        border: 2rpx solid $dividerColor;
        background-color: #ecf0f1;
        font-size: $font-size-base;
        margin-top: 20rpx;

        &-left {
          display: flex;
          justify-content: center;
          flex-direction: column;
          flex: 0.8;
          border-right: 2rpx solid $dividerColor;
          height: 100%;
          padding-left: 10rpx;
        }
        &-right {
          flex: 0.2;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
  &-box {
    margin-bottom: 50rpx;
    &-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 700;
      margin-bottom: 30rpx;
      .title {
        font-size: $font-size-xxxlarge;
      }
      .right {
        display: flex;
        font-size: $font-size-middle;
        .add-ad {
          color: $themeComColor;
          margin-left: 20rpx;
        }
      }
    }
    &-main {
      width: 100%;
      padding: 20rpx;
      background-color: #f2f2f2;
      border-radius: 20rpx;
      &-item {
        position: relative;
        font-size: $font-size-middle;
        color: $textBlack;
        .swiper-box {
          width: 100%;
          height: 340rpx;
          .img {
            width: 100%;
            height: 300rpx;
          }
          .clear {
            position: absolute;
            right: 0;
            top: 40rpx;
          }
        }
        .box-img {
          position: relative;
          width: 100%;
          .img {
            width: 100%;
          }
          .clear {
            position: absolute;
            right: -20rpx;
            top: -20rpx;
          }
        }
      }
      .content-txt {
        font-size: $font-size-xlarge;
        .clear {
          position: absolute;
          right: -20rpx;
          top: -20rpx;
        }
      }
    }
  }
}
.fixed-btn {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  background-color: $uni-bg-color;
  z-index: 99999;
}
</style>